//
//  GPLangCache.m
//  YueYue
//
//  Created by LiuYu on 2024/10/24.
//

#import "GPLangCache.h"
#import "YMTranslacteRequest.h"

@interface GPLangCache ()
@property (nonatomic,   strong) YMTranslacteRequest *transRequest;
@end

@implementation GPLangCache

+ (instancetype)shareInstance
{
    static GPLangCache * __shareInstance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __shareInstance = [GPLangCache.alloc init];
    });
    
    return __shareInstance;
}

- (YMTranslacteRequest *)transRequest
{
    if (!_transRequest) {
        _transRequest = [YMTranslacteRequest.alloc initWithType:YMTranslacteRequestTypeGetUserLang];
    }
    return _transRequest;
}

- (NSMutableDictionary *)langsCache
{
    if (!_langsCache) {
        _langsCache = [NSMutableDictionary dictionary];
    }
    return _langsCache;
}

- (void)setLang:(NSString *)lang forUser:(NSString *)userID clientID:(nonnull NSString *)clientID
{
    if (lang && userID && clientID) {
        NSString *key = [clientID stringByAppendingFormat:@"|%@", userID];
        [self.langsCache setObject:lang forKey:key];
    }
}

- (void)fetchLangForKey:(NSString *)userID clientID:(NSString *)clientID completion:(void (^)(NSString * _Nonnull))completion
{
    if (!userID || !clientID) {
        return;
    }
    
    NSString *key = [clientID stringByAppendingFormat:@"|%@", userID];
    NSString *obj = [self.langsCache objectForKey:key];
    
    if (obj) {
        completion(obj);
        return;
    }
    
    self.transRequest.params = @{@"userId" : userID, @"clientId" : clientID};
    [self.transRequest startWithCompletionBlockWithSuccess:^(__kindof YMTranslacteRequest * _Nonnull request) {
        if (request.isSuccess) {
            NSString *lang = request.result[@"data"];
            if (lang) {
                [self.langsCache setObject:lang forKey:key];
                completion(lang);
            }
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}

- (void)clear
{
    [self.langsCache removeAllObjects];
}

@end
